package com.win.config;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.messaging.SessionConnectedEvent;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;

import java.security.Principal;

@Configuration
// @EnableWebSocketMessageBroker 注解用于开启使用 STOMP 协议来传输基于代理（MessageBroker）的消息，
// 这时候控制器(controller) 开始支持@MessageMapping,就像是使用 @requestMapping 一样。
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    private static final Logger log = LoggerFactory.getLogger(WebSocketConfig.class);

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        //注册一个名为 /ws 的 Stomp 节点(endpoint),并指定使用 SockJS 协议。
        registry.addEndpoint("/ws").setAllowedOrigins("*").withSockJS();
        //注册一个名为 /log 的 Stomp 节点(endpoint),并指定使用 SockJS 协议。
        //registry.addEndpoint("/log").withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        // 设置接收客户端消息 的 路径前缀（不设置可以）
//        registry.setApplicationDestinationPrefixes("/app");

        // 设置接收 客户端订阅 的 路径前缀（可以为空串）
        // 当有值是,  必须 和 controller -> @SendTo 配置的地址 前缀一样/全匹配
        registry.enableSimpleBroker("");
    }

    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        // 添加拦截器，处理客户端发来的请求
        // registration.interceptors(new WebSocketHandleInterceptor());
    }


    @EventListener
    public void handleConnectListener(SessionConnectedEvent event) {
        StompHeaderAccessor accessor = StompHeaderAccessor.wrap(event.getMessage());
        Principal user = accessor.getUser();
        log.info("[ws-connected] socket connect: {}, user:{}", event.getMessage(), user);
    }

    @EventListener
    public void handleDisconnectListener(SessionDisconnectEvent event) {
        StompHeaderAccessor accessor = StompHeaderAccessor.wrap(event.getMessage());
        Principal user = accessor.getUser();
        log.info("[ws-disconnect] socket disconnect: {}, user:{}", event.getMessage(), user);

    }
}
